package com.garden.rocketmq.learn.demo.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 延时消费者 延时消费消息
 * Created by Garden on 2020-08-11 21:46
 */
public class ScheduledMessageConsumer {

    public static void main(String[] args) throws MQClientException {
        //实例化消费者Consumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("scheduled_message_consumer_group");
        //设置NameServer的地址，Consumer启动后通过NameServer获取目标Topic的路由信息
        consumer.setNamesrvAddr("localhost:9876");
        //订阅消息，可订阅一个或多个Topic以及通过Tag过滤消息
        consumer.subscribe("test_topic","*");
        //注册回调实现类来处理从broker拉取回来的消息
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                //查看消费每个消息消费的时间与消息存储时间
                msgs.forEach(messageExt -> {
                    long consumerTimestamp = System.currentTimeMillis();
                    long storeTimestamp = messageExt.getStoreTimestamp();
                    System.out.println("消息messageId=" + messageExt.getMsgId()
                            + " 消费时间：" + consumerTimestamp + " 存储时间：" + storeTimestamp
                            + " 相差" + (consumerTimestamp - storeTimestamp) + "ms消费");
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }

}
